package cn.fbs.service;

import cn.fbs.dao.dm.DMCodeCategoryTypeMapper;
import cn.fbs.dao.dm.DMLabelGroupInfoMapper;
import cn.fbs.model.TLabelGroupInfo;
import cn.fbs.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LabelGroupService {
    @Autowired
    private DMLabelGroupInfoMapper mapper;
    @Autowired
    private DMCodeCategoryTypeMapper categoryMapper;

    public List<TLabelGroupInfo> findAll() {
        List<TLabelGroupInfo> list = mapper.findAll();
        return list;
    }
    public Result insert(TLabelGroupInfo targetType) {
        Result result = new Result();
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString().replace("-", "");
        targetType.setId(uuidStr);
        targetType.setCreateDate(new Date());
        //非固有标签
        targetType.setIsInherent(new Byte("0"));

        String name = targetType.getName();
       int count =  mapper.selectCountByName(name);
       if (count==0){
           //没有相同的标签，添加标签组
           mapper.insert(targetType);
           result.setCode(200);
           result.setMsg("新增标签组成功");
           return result;
       }else {
           //有相同的标签，无法添加
           result.setCode(500);
           result.setMsg("名称相同，无法添加");
           return result;
       }

    }
    public Result update(TLabelGroupInfo groupInfo) {

        Result result = new Result();
        groupInfo.setUpdateDate(new Date());
//        int count =  mapper.selectCountByName(targetType.getName());
        int count =  mapper.selectCountByNameAndId(groupInfo.getName(),groupInfo.getId());

        if (count==0){
            //没有相同的标签，修改标签组
            mapper.updateByPrimaryKeySelective(groupInfo);
            result.setCode(200);
            result.setMsg("重命名标签组成功");
            return result;
        }else {
            //有相同的标签，无法添加
            result.setCode(500);
            result.setMsg("名称相同，无法修改");
            return result;
        }

    }
    public String delete(String primaryKey) {

        TLabelGroupInfo tLabelGroupInfo = mapper.selectByPrimaryKey(primaryKey);
        Byte isInherent = tLabelGroupInfo.getIsInherent();
        Integer integer = Integer.valueOf(isInherent);
        if (integer==1){
            return "属于固有标签组，无法删除";
        }
        /**
         * 删除类型之前，确定类型下没有标签
         */
        Integer count=categoryMapper.countByGroupId(primaryKey);
        if (count>=1){
            return "标签分类下存在标签，请先删除标签";
        }
        mapper.deleteByPrimaryKey(primaryKey);
        return "删除成功";
    }

    public TLabelGroupInfo getGroupInfo(String id) {
        TLabelGroupInfo tLabelGroupInfo = mapper.selectByPrimaryKey(id);
        return tLabelGroupInfo;
    }
}
